package org.yzh.codec;

import io.github.yezhihao.protostar.util.Explain;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.springframework.util.StringUtils;
import org.yzh.protocol.JT808Beans;
import org.yzh.protocol.basics.JTMessage;
import org.yzh.protocol.codec.JTMessageAdapter;

/**
 * 解码分析
 * @author yezhihao
 * https://gitee.com/yezhihao/jt808-server
 */
public class Elucidator extends JT808Beans {

    public static final JTMessageAdapter coder = new JTMessageAdapter("org.yzh.protocol");

    public static void main(String[] args) {
        String hex = "7e000440000100000000001234567890ffffdd7e";

        hex=StringUtils.trimAllWhitespace(hex);
        // JTMessage msg = H2019(T0200());
        JTMessage msg = decode(hex);
        // hex = encode(msg);


        hex = "7E 80 04 40 06 01 00 00 00 00 00 12 34 56 78 90 00 00 23 11 09 16 52 37 13 7E";
        hex=StringUtils.trimAllWhitespace(hex);
        msg = decode(hex);
    }

    public static void main2() {
        JTMessage msg = H2019(T0200());
        String hex = encode(msg);
        System.out.println("hex = " + hex);
    }

    private static String encode(JTMessage message) {
        System.out.println("====================================================================================\n");
        Explain explain = new Explain();
        ByteBuf buf = null;
        try {
            buf = coder.encode(message, explain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String hex = ByteBufUtil.hexDump(buf);
        System.out.println(message);
        System.out.println(hex);
        explain.println();
        return hex;
    }

    /**
     * 解码
     * @param hex
     * @return
     */
    private static JTMessage decode(String hex) {
        System.out.println("====================================================================================\n");
        Explain explain = new Explain();
        JTMessage message = null;
        try {
            message = coder.decode(Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hex)), explain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(message);
        System.out.println(hex);
        explain.println();
        return message;
    }
}